package naga.x.platform2.channel.q724;

import java.util.Map;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import com.alibaba.fastjson.JSON;

import naga.x.platform2.app.AppErrorController;
import naga.x.platform2.app.Channel;
import naga.x.platform2.app.model.Recharge;
import naga.x.platform2.app.model.RechargeTemplate;
import naga.x.platform2.app.support.GameServerSupport;
import naga.x.platform2.app.support.RechargeSupport;
import naga.x.platform2.channel.q724.support.PayExt;
import naga.x.platform2.channel.q724.support.Q724Api;
import naga.x.platform2.channel.q724.support.Q724Config;
import naga.x.platform2.support.RequestPath;
import naga.x.platform2.utils.CommonUtils;
import naga.x.platform2.utils.HttpUtils;
import naga.x.platform2.utils.IOUtils;
import naga.x.platform2.utils.NumberUtils;
import naga.x.platform2.utils.UUID;

/**
 * 7724
 * @see <a href="http://open.7724.com/">http://open.7724.com/</a>
 * @author yang.li
 *
 */
@Controller
public class Q724Controller {
	
	@Autowired
	private Q724Config config;
	@Autowired
	private RechargeSupport support;
	@Autowired
	private GameServerSupport gameServers;
	
	private static Channel channel = Channel.Q724;
	
	private static final Logger LOG = LoggerFactory.getLogger(Q724Controller.class);

	@RequestMapping(path = RequestPath.Q724_USER_INFO, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object getUserInfo(String uid) {
		Map<String, String> params = new TreeMap<>();
		params.put("appkey", config.getAppKey());
		params.put("time", String.valueOf(System.currentTimeMillis()));
		params.put("uid", uid);
		params.put("sign", Q724Api.makeSign(params, "qqes", true));
		
		return HttpUtils.post(config.getAccUrl(), params);
	}
	
	@RequestMapping(path = RequestPath.Q724_PAY)
	public String pay(Integer sid, Long pid, Integer product, String channel, String token) {
		if (gameServers.get(sid) == null) {
			return UrlBasedViewResolver.REDIRECT_URL_PREFIX + AppErrorController.PATH + "?msg=sid error:" + sid;
		}
		RechargeTemplate template = support.getTemplate(product);
		if (template == null) {
			return UrlBasedViewResolver.REDIRECT_URL_PREFIX + AppErrorController.PATH + "?msg=product error:" + product;
		}
		Map<String, String> params = new TreeMap<String, String>();
//		appkey
//		游戏AppKey
		params.put("appkey", config.getAppKey());
//		channel
//		用户登录时接收的进入游戏的标识
		params.put("channel", channel);
//		fee
//		订单金额,单位元
		params.put("fee", String.valueOf(template.getPrice()));
//		orderno
//		游戏平台订单号【唯一】（游戏商生成）
		params.put("orderno", UUID.randomUUID().toString());
//		subject
//		主题
		params.put("subject", template.getName());
//		time
//		当前请求时间
		params.put("time", String.valueOf(System.currentTimeMillis()));
//		token
//		用户玩家token
		params.put("token", token);
//		sign
//		签名
		params.put("sign", Q724Api.makeSign(params, config.getPayKey(), true));
//		ext
//		透传信息，不参与验签。
//		如果可能，请至少传递以下信息，方便我们运营：
//		    格式：{"rolename":"角色名","server":服务器,"roleid":"角色id"} 
//		rolename=角色名;server=服务器区;roleid=游戏内角色id（非7724 uid），无id为空
//		若游戏没有多服务器不分区，默认为1区
		params.put("ext", CommonUtils.encodeURL(JSON.toJSONString(new PayExt(sid, pid, product)), IOUtils.UTF8));
		
//		UrlBasedViewResolver#REDIRECT_URL_PREFIX
//		HttpUtils.sendRedirect(response, Q724Api.URL_PAY + '?' + HttpUtils.wrapQueryString(params));
		return UrlBasedViewResolver.REDIRECT_URL_PREFIX + config.getPayUrl() + '?' + HttpUtils.wrapQueryString(params);
	}
	
	@RequestMapping(path = RequestPath.Q724_PAY_CALLBACK, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public String payCallback(String appkey, String fee, String orderno, String qqes_orderno, String success, String time, String token, String sign, String ext) {
		Map<String, String> params = new TreeMap<String, String>();
//		appkey
//		游戏AppKey
		params.put("appkey", appkey);
//		fee
//		支付的金额 
		params.put("fee", fee);
//		orderno
//		商家自己的订单号
		params.put("orderno", orderno);
//		qqes_orderno
//		七七游订单号
		params.put("qqes_orderno", qqes_orderno);
//		success
//		交易是否成功，1表示成功
		params.put("success", success);
//		time
//		当前时间签名
		params.put("time", time);
//		token
//		用户玩家token 
		params.put("token", token);
//		sign
//		签名 
		ext = CommonUtils.decodeURL(ext, IOUtils.UTF8);
		String s = Q724Api.makeSign(params, config.getCallbackKey(), true);
		if (!s.equals(sign)) {
			LOG.info("[7724 PAY ERR]APPKEY[{}]FEE[{}]ORDER[{}]77ORDER[{}]SUCC[{}]TIME[{}]TOKEN[{}]SIGN[{}]EXT[{}]CAUSE[SIGNERR]", appkey, fee, orderno, qqes_orderno, success, time, token, sign, ext);
			return "FAIL";
		}
		if (!"1".equals(success)) {
			LOG.info("[7724 PAY ERR]APPKEY[{}]FEE[{}]ORDER[{}]77ORDER[{}]SUCC[{}]TIME[{}]TOKEN[{}]SIGN[{}]EXT[{}]CAUSE[FAIL]", appkey, fee, orderno, qqes_orderno, success, time, token, sign, ext);
			return "OK";
		}
//		ext
//		透传信息，不参与验签
		PayExt extObj = JSON.parseObject(ext, PayExt.class);
		RechargeTemplate template = extObj != null ? support.getTemplate(extObj.product) : null;
		if (template == null) {
			LOG.info("[7724 PAY ERR]APPKEY[{}]FEE[{}]ORDER[{}]77ORDER[{}]SUCC[{}]TIME[{}]TOKEN[{}]SIGN[{}]EXT[{}]CAUSE[PRODUCT NULL]", appkey, fee, orderno, qqes_orderno, success, time, token, sign, ext);
			return "OK";
		}
		Recharge recharge = new Recharge(channel.prefix + qqes_orderno, extObj.roleid, extObj.server, NumberUtils.parseInt(fee), -1, template.getId(), channel.name);
		recharge.setAttach(orderno); // 己方的订单号
		support.offer(recharge);
		LOG.info("[7724 PAY SUCC]APPKEY[{}]FEE[{}]ORDER[{}]77ORDER[{}]SUCC[{}]TIME[{}]TOKEN[{}]SIGN[{}]EXT[{}]", appkey, fee, orderno, qqes_orderno, success, time, token, sign, ext);
		return "OK";
	}
	
	@RequestMapping(path = RequestPath.Q724_INVITE_CALLBACK, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public void inviteCallback(String suid, String iuid, Long timestamp, String sign) {
//		suid
//		邀请者uid
//		iuid
//		被邀请者uid
//		timestamp
//		时间戳
//		sign
//		暂时不用验证签名
	}
	
}
